<template>
  <el-dialog
    v-if="dialogFormVisible"
    :visible.sync="dialogFormVisible"
    width="900px"
    @close="close"
  >
    <template slot="title">
      <div>
        <svg-icon icon-class="program-add" />
        <span>{{ title }}</span>
      </div>
    </template>
    <el-form
      ref="form"
      :inline="true"
      :model="form"
      :rules="rules"
      class="demo-form-inline"
      label-width="30%"
    >
      <el-divider>
        <span style="color: #b5b4b4">编码信息</span>
      </el-divider>

      <el-form-item
        :label="tempDesc.organization"
        prop="organization"
        class="formItem normalInput"
      >
        <el-select
          v-model="form.organization"
          placeholder="请选择"
          :disabled="dialogStatus != 'create'"
        >
          <el-option
            v-for="item in orgs"
            :key="item.itemText"
            :label="item.itemValue"
            :value="item.itemText"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        :label="tempDesc.modelNum"
        prop="modelNum"
        class="formItem normalInput"
      >
        <el-input
          v-model="form.modelNum"
          :disabled="dialogStatus != 'create'"
        ></el-input>
      </el-form-item>
      <el-form-item
        :label="tempDesc.speciality"
        prop="speciality"
        class="formItem normalInput"
      >
        <el-select
          v-model="form.speciality"
          placeholder="请选择"
          :disabled="dialogStatus != 'create'"
        >
          <el-option
            v-for="item in spes"
            :key="item.itemText"
            :label="item.itemValue"
            :value="item.itemText"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        :label="tempDesc.modelNumPart"
        prop="modelNumPart"
        class="formItem normalInput"
      >
        <el-input
          v-model="form.modelNumPart"
          :disabled="dialogStatus != 'create'"
        ></el-input>
      </el-form-item>
      <el-form-item
        :label="tempDesc.versionNum"
        prop="versionNum"
        class="formItem normalInput"
      >
        <el-input
          v-model="form.versionNum"
          :disabled="dialogStatus != 'create'"
        ></el-input>
      </el-form-item>
      <el-form-item
        :label="tempDesc.freeNum"
        prop="freeNum"
        class="formItem normalInput"
      >
        <el-input
          v-model="form.freeNum"
          :disabled="dialogStatus != 'create'"
        ></el-input>
      </el-form-item>
      <el-form-item
        v-if="dialogStatus === 'create'"
        align="right"
        class="formItem"
        style="width: 100%"
      >
        <el-button
          icon="el-icon-coordinate"
          type="primary"
          @click="create_pre_id"
        >
          生成程序编号
        </el-button>
      </el-form-item>
      <el-divider>
        <span style="color: #b5b4b4">基本信息</span>
      </el-divider>
      <el-form-item
        :label="tempDesc.preId"
        label-width="14%"
        prop="preId"
        class="longInput"
      >
        <el-input v-model="form.preId" disabled></el-input>
      </el-form-item>
      <el-form-item
        :label="tempDesc.name"
        prop="name"
        class="formItem normalInput"
      >
        <el-input v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item
        :label="tempDesc.hostIp"
        prop="hostIp"
        class="formItem normalInput"
      >
        <el-input v-model="form.hostIp"></el-input>
      </el-form-item>
      <el-form-item
        :label="tempDesc.installationDir"
        prop="installationDir"
        class="formItem normalInput"
      >
        <el-input v-model="form.installationDir"></el-input>
      </el-form-item>
      <el-form-item
        :label="tempDesc.description"
        prop="description"
        class="formItem normalInput"
      >
        <el-input v-model="form.description"></el-input>
      </el-form-item>
      <el-form-item
        :label="tempDesc.shell"
        prop="shell"
        class="formItem normalInput"
      >
        <el-input v-model="form.shell"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { getAction, postAction } from '@/api/action'

  // 常量title
  const tempDesc = {
    id: '',
    preId: '程序编号',
    name: '程序名称',
    status: '状态',
    hostIp: '主机ip',
    installationDir: '安装地址',
    description: '描述',
    createTime: '创建时间',
    dataType: '数据类型',
    organization: '组织',
    modelNum: '型号',
    speciality: '专业',
    modelNumPart: '部件',
    versionNum: '版本编号',
    freeNum: '自由编号',
    createrPreId: '创建人',
    createTime6: '创建时间',
    specialityName: '专业名称',
    organizationName: '组织名称',
    shell: 'shell调用',
  }
  export default {
    name: 'ProgramManagementEdit',
    data() {
      //自定义校验规则
      var maxSize = (rule, value, callback) => {
        if (!value && rule.field != 'freeNum') {
          return callback(new Error('不能为空'))
        }
        let maxLength = 6 //最大位数,默认6位
        if (rule.field == 'organization') {
          maxLength = 5
        }
        if (rule.field == 'freeNum') {
          maxLength = 30
          if ((value = '')) {
            this.modelForm[rule.field] = ''
          }
        }
        if (value.length > maxLength) {
          return callback(new Error('不能大于' + maxLength + '位数'))
        } else {
        }
        callback()
      }
      //不能为空
      var blankSpace = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('不能为空'))
        }
        callback()
      }
      //校验ip地址
      var isIP = (rule, value, callback) => {
        var reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/
        if (!reg.test(value)) {
          return callback(new Error('请输入正确IP地址！'))
        }
        callback()
      }
      return {
        tempDesc: tempDesc,
        //必须给form的属性默认值，不然有问题
        form: {
          preId: undefined,
          name: undefined,
          installationDir: undefined,
          description: undefined,
          speciality: undefined,
          hostIp: undefined,
          dataType: undefined,
          organization: undefined,
          modelNum: undefined,
          modelNumPart: undefined,
          versionNum: undefined,
          freeNum: undefined,
          createrPreId: undefined,
          createTime6: undefined,
          specialityName: undefined,
          organizationName: undefined,
          creareUser: undefined,
        },
        rules: {
          organization: [
            { validator: maxSize, trigger: 'change' },
            { required: true, trigger: 'blur' },
          ],
          modelNum: [
            { validator: maxSize, trigger: 'blur' },
            { required: true, trigger: 'blur' },
          ],
          speciality: [
            { validator: maxSize, trigger: 'change' },
            { required: true, trigger: 'blur' },
          ],
          modelNumPart: [
            { validator: maxSize, trigger: 'blur' },
            { required: true, trigger: 'blur' },
          ],
          versionNum: [
            { validator: maxSize, trigger: 'blur' },
            { required: true, trigger: 'blur' },
          ],
          freeNum: [{ validator: maxSize, trigger: 'blur' }],
          name: [
            { validator: blankSpace, trigger: 'blur' },
            { required: true, trigger: 'blur' },
          ],
          preId: [
            { validator: blankSpace, trigger: 'change' },
            { required: true, trigger: 'blur' },
          ],
          hostIp: [
            { validator: blankSpace, trigger: 'blur' },
            { validator: isIP, trigger: 'blur' },
            {
              required: true,
              trigger: 'blur',
            },
          ],
          installationDir: [
            { validator: blankSpace, trigger: 'blur' },
            { required: true, trigger: 'blur' },
          ],
        },
        title: '',
        dialogFormVisible: false,
        dialogStatus: 'create',
        orgs: [], //modelForm中organization组织选项列表
        spes: [], //modelForm中speciality专业选项列表
        url: {
          listPage: '/presoftasim/resourcedata/program/listpage',
          delete: '/presoftasim/resourcedata/program/delete',
          create: '/presoftasim/resourcedata/program/create',
          update: '/presoftasim/resourcedata/program/update',
          createPreId: '/presoftasim/resourcedata/program/createPreId',
          getModelFromSelects:
            '/presoftasim/resourcedata/program/getModelFromSelects',
        },
      }
    },
    methods: {
      showEdit(row) {
        if (!row) {
          this.title = '创建程序'
          this.dialogStatus = 'create'
          this.getModelFromSelects()
          this.form = {}
        } else {
          this.title = '编辑程序'
          this.form = Object.assign({}, row)
          this.dialogStatus = 'update'
        }
        this.dialogFormVisible = true
      },
      close() {
        this.dialogFormVisible = false
        this.$refs['form'].clearValidate()
      },
      save() {
        this.$refs['form'].validate(async (valid) => {
          if (valid) {
            let obj = Object.assign({}, this.form)
            this.close()
            this.$emit('fetch-data', obj)
          } else {
            return false
          }
        })
      },
      //生成72位编码
      create_pre_id() {
        //校验表单输入书否符合要求，若全部符合才向服务端发起请求
        let handle = true
        console.log(this.$refs['form'])
        this.$refs['form'].validateField(
          [
            'organization',
            'modelNum',
            'speciality',
            'modelNumPart',
            'versionNum',
            'freeNum',
          ],
          (errmessage) => {
            if (errmessage != '') {
              handle = false
              return console.log(errmessage)
            }
          }
        )
        if (handle) {
          this.form.createUser = this.$store.state.user.id
          postAction(this.url.createPreId, this.form)
            .then((response) => {
              if (response.code === 200) {
                console.log(response)
                this.form.preId = response.data.preId
                this.form.createrPreId = response.data.createrPreId
                this.form.createTime6 = response.data.createTime6
                this.form.dataType = response.data.dataType
                if (this.form.freeNum == '' || this.form.freeNum == undefined) {
                  this.form.freeNum = response.data.freeNum
                }
                console.log(this.form)
                this.getValue()
              } else {
                this.submitFail(response.message)
              }
            })
            .catch((err) => {
              console.log(err)
            })
        }
      },
      //获取组织、专业名称
      getValue() {
        for (let i in this.orgs) {
          if (this.form.organization == this.orgs[i].itemText) {
            this.form.organizationName = this.orgs[i].itemValue
          }
        }
        for (let i in this.spes) {
          if (this.form.speciality == this.spes[i].itemText) {
            this.form.specialityName = this.spes[i].itemValue
          }
        }
      },
      //获取组织、专业选择列表
      getModelFromSelects() {
        console.log(this.url.ModelFromSelects)
        getAction(this.url.getModelFromSelects, this.form)
          .then((response) => {
            if (response.code === 200) {
              this.orgs = response.data.organization
              this.spes = response.data.speciality
            } else {
              this.submitFail(response.message)
            }
          })
          .catch((err) => {
            console.log(err)
          })
      },
    },
  }
</script>
<style lang="scss">
  .formItem {
    width: 45%;
  }
  .normalInput .el-form-item__content {
    width: 70%;
    margin: 0px;
  }
  .el-form-item {
    margin-right: 0px;
  }
  .longInput {
    width: 100%;
  }
  .longInput .el-form-item__content {
    width: 77%;
  }
  .el-select {
    width: 100%;
    margin: 0px;
  }
</style>
